package com.it.controller;

import cn.dev33.satoken.util.SaResult;
import com.it.annotation.SystemLog;
import com.it.bean.Document;
import com.it.service.DocumentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/document")
@RequiredArgsConstructor
public class DocumentController {

    private final DocumentService documentService;


    @PostMapping("/upload")
    @SystemLog(value = "文件管理", method = "文件上传")
    public SaResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        Document document = documentService.upload(file);
        return SaResult.data(document);
    }

    @PostMapping("/uploads")
    @SystemLog(value = "文件管理", method = "文件上传")
    public SaResult uploads(@RequestParam("files") MultipartFile[] files) throws IOException {
        List<Document> documents = documentService.uploads(files);
        return SaResult.data(documents);
    }

    @GetMapping("/read/{uuid}")
    @SystemLog(value = "文件管理", method = "文件读取")
    public ResponseEntity<byte[]> read(@PathVariable("uuid") String uuid) throws IOException {
        byte[] image = documentService.read(uuid);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(image);
    }

    @GetMapping("/download/{fileName}")
    @SystemLog(value = "文件管理", method = "文件下载")
    public ResponseEntity<byte[]> download(@PathVariable("fileName") String fileName) throws IOException {
        byte[] image = documentService.read(fileName);
        return ResponseEntity.ok()
                .body(image);
    }
}
